//
//  ByUIDataImportVC.m
//  laserdevice_ios
//
//  Created by pro on 16/12/13.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByUIDataImportVC.h"

// handle
#import "ByBlueToothHandleModel.h"          // 蓝牙执行者
#import "ByBlueToothDataOperationModel.h"   // 蓝牙数据处理者
#import "ByExcelBaseView.h"                 // excel数据基类

// vc
#import "ByUIDataImportHistoryVC.h"         // 数据导入历史

// 数据测量model
#import "ByBlueToothMeaturesL1Model.h"          // 单次测量
#import "ByBlueToothMeaturesL2Model.h"          // 单次测量
#import "ByBlueToothMeaturesL3Model.h"          // 单次测量
#import "ByBlueToothMeaturesG1Model.h"          // 单次勾股
#import "ByBlueToothMeaturesG2Model.h"          // 双次勾股加
#import "ByBlueToothMeaturesG3Model.h"          // 双次勾股减
#import "ByBlueToothMeaturesS1Model.h"          // 长方形面积
#import "ByBlueToothMeaturesS2Model.h"          // 三角形面积
#import "ByBlueToothMeaturesS3Model.h"          // 梯形面积
#import "ByBlueToothMeaturesV1Model.h"          // 长方体体积
#import "ByBlueToothMeaturesH1Model.h"          // 直角测量
#import "ByBlueToothMeaturesH2Model.h"          // 直角测量
#import "ByBlueToothMeaturesX1Model.h"          // 距离+水平
#import "ByBlueToothMeaturesP1Model.h"          // 加法
#import "ByBlueToothMeaturesM1Model.h"          // 减法

@interface ByUIDataImportVC ()

// data
@property (nonatomic, strong) NSMutableString *dataString;  // 数据字符串

// view
@property (nonatomic, strong) ByExcelBaseView *excel;       // 表格视图

@end

@implementation ByUIDataImportVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = STRING(@"shujudaoru");
    
    self.view.backgroundColor = rgba(3, 41, 84, 1);
    
    [self addBYItemviews:@[STRING(@"lishishuju")] mode:ByNavigationItemModeImageAndText position:ByNavigationItemPositionModeRight];
    self.tintColor = [UIColor whiteColor];
    
    [self addLeftBackBarButtonItem];
    
    if (![ByBlueToothHandleModel shareInstance].characteristic) {
        [ByCoreToolAlert showFailureWithText:STRING(@"qinglianjielanya")];
        return;
    }
    
    [self getHistoryMeasures];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [[ByBlueToothHandleModel shareInstance] closeHistoryMeasure];
    
    // 如果再退出这个界面的时候还没有创建视图，就不用创建了
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    
    [ByCoreToolAlert hideHud];
}

#pragma mark - 获得蓝牙数据
- (void)getHistoryMeasures {
    
    self.dataString = [[NSMutableString alloc] init];

    // 正式版需要，测试的时候不惜要
    [ByCoreToolAlert showLoadind:STRING(@"zhengzaidaorushuju")];
    
    [[ByBlueToothHandleModel shareInstance] getHistoryMeasure:^(NSString *dataHex) {
        
        // 拼接数据
        [self.dataString appendString:dataHex];

        // 如果能再次收到数据，则不用绘制图标
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        // 如果3秒内无法再收到数据，则默认数据完毕
        [self performSelector:@selector(operationHistoryData) withObject:nil afterDelay:3];
    }];
}
- (void)operationHistoryData {
    
    [self createExcel];     // 创建表格
    
    // 给图标设置测量字典
    self.excel.meatureModelsDic = [ByBlueToothDataOperationModel historyDataOperation:self.dataString];
    
    // 停止接收数据
    [[ByBlueToothHandleModel shareInstance] closeHistoryMeasure];

}


#pragma mark - 创建表格
- (void)createExcel {
    
    self.excel = [[ByExcelBaseView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 100)];
    [self.view addSubview:self.excel];
    
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.frame = CGRectMake(20, self.excel.bottom + 30, SCREEN_WIDTH - 40, 40);
    saveButton.backgroundColor = CJ_THEME_COLOR;
    saveButton.titleLabel.font = FONT(15);
    saveButton.layer.cornerRadius = 4;
    [saveButton setTitle:STRING(@"baocun") forState:UIControlStateNormal];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton setImage:[UIImage imageNamed:@"real-time_baocun"] forState:UIControlStateNormal];
    [saveButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 3, 0, -3)];
    [saveButton setImageEdgeInsets:UIEdgeInsetsMake(0, -3, 0, 3)];
    [saveButton addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];
}


#pragma mark - 点击事件
- (void)leftItemsAction:(NSInteger)leftIndex {
    
    if (!self.excel.saveDic) {
        [super leftItemsAction:leftIndex];
        return;
    }
    
    [UIAlertView showWithTitle:STRING(@"tuichu") message:STRING(@"tuichuqianshifoubaocun") cancelButtonTitle:STRING(@"zhijietuichu") otherButtonTitles:@[STRING(@"xianbaocun")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [super leftItemsAction:leftIndex];
            return;
        } else {
            [self performSelector:@selector(save:) withObject:nil afterDelay:0.5];
        }
    }];
    
    
}
- (void)rightItemsAction:(NSInteger)rightIndex {
    
    ByUIDataImportHistoryVC *vc = [[ByUIDataImportHistoryVC alloc] init];
    vc.backAction = ^ (NSDictionary *jsonDic) {
        
        NSMutableDictionary *measureDic = [[NSMutableDictionary alloc] init];
        NSArray *type_list = jsonDic[@"type_list"];
        for (NSDictionary *typeDic in type_list) {
            NSString *type = typeDic[@"type"];
            NSArray *element_list = typeDic[@"element_list"];
            NSMutableArray *models = [[NSMutableArray alloc] init];
            for (NSDictionary *ele_dic in element_list) {
                ByBlueToothMeaturesModel *model = nil;
                if ([type isEqualToString:@"L1"]) {
                    model = [[ByBlueToothMeaturesL1Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"L2"]) {
                    model = [[ByBlueToothMeaturesL2Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"L3"]) {
                    model = [[ByBlueToothMeaturesL3Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"G1"]) {
                    model = [[ByBlueToothMeaturesG1Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"G2"]) {
                    model = [[ByBlueToothMeaturesG2Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"G3"]) {
                    model = [[ByBlueToothMeaturesG3Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"S1"]) {
                    model = [[ByBlueToothMeaturesS1Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"S2"]) {
                    model = [[ByBlueToothMeaturesS2Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"S3"]) {
                    model = [[ByBlueToothMeaturesS3Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"V1"]) {
                    model = [[ByBlueToothMeaturesV1Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"H1"]) {
                    model = [[ByBlueToothMeaturesH1Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"H2"]) {
                    model = [[ByBlueToothMeaturesH2Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"X1"]) {
                    model = [[ByBlueToothMeaturesX1Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"P1"]) {
                    model = [[ByBlueToothMeaturesP1Model alloc] initWithJsonDic:ele_dic];
                }
                if ([type isEqualToString:@"M1"]) {
                    model = [[ByBlueToothMeaturesM1Model alloc] initWithJsonDic:ele_dic];
                }
                [models addObject:model];
            }
            
            [measureDic setObject:models.copy forKey:type];
        }
        
        
        if (!self.excel) {
            [self createExcel];     // 创建表格
        }
        self.excel.meatureModelsDic = measureDic;
    };
    
    [self by_normalPush:vc hasNavi:YES];
}
- (void)save:(UIButton *)sender {
    
    [UIAlertView showWithTitle:nil
                       message:STRING(@"wei excel mingming")
                         style:UIAlertViewStylePlainTextInput
                   defaultText:[NSDate getCurrentDateForStringFormatWithFormatter:nil]
             cancelButtonTitle:STRING(@"quxiao")
             otherButtonTitles:@[STRING(@"queding")]
                      tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        UITextField *tf = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            
            NSMutableDictionary *tempDic = self.excel.saveDic;
            [tempDic setObject:tf.text forKey:@"name"];
            
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tempDic.copy options:NSJSONWritingPrettyPrinted error:nil];
            
            [ByFileManager saveHistoryWithName:tf.text
                                          json:jsonData
                                       existed:^{
                                         
                                           NSLog(@"文件夹已经存在");
                                       }
                                       failure:^(NSError *error) {
                                         
                                           NSLog(@"保存失败");
                                       }];
            if (sender == nil) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
    }];

}

@end
